﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ovvio.Data;

namespace Ovvio.Business
{
    public static class OvvioSettings
    {
        public static void Setup()
        {
            if (!IsAdministratorSetup)
            {
                var service = new UserService();

                var entity = service.GetEntity(p => p.Username.ToUpper() == "ADMINISTRATOR");

                if (entity == null)
                    entity = service.Create();

                entity.Username = "Administrator";
                entity.FirstName = "John";
                entity.LastName = "Smith";
                entity.Mobile = "01234567";
                entity.IsActive = true;
                entity.UpdatedBy = "Administrator";
                entity.RegistrationDate = DateTime.Now;
                entity.IsNewsLetterSubscriber = false;
                entity.Email = "administrator@ovvio.com";
                entity.Role = (short)Role.Admin;
                entity.SetPassword("admin");
                service.Save(entity, -1);

                IsAdministratorSetup = true;
            }
        }

        public static bool IsAdministratorSetup
        {
            get
            {
                bool returnValue = false;
                using (var ctx = new OvvioDataContext())
                {
                    var query = from s in ctx.Settings
                                where s.Tag.Equals("IsAdministratorSetup")
                                select s;
                    
                    if (query.Any())
                    {
                        var record = query.First();
                        if (!bool.TryParse(record.Value, out returnValue))
                        {
                            record.Value = "False";
                            ctx.SaveChanges();
                        }
                        
                    }
                    else
                    {
                        var newRecord = new Setting() { Tag = "IsAdministratorSetup", Value = "False" } ;
                        ctx.AddToSettings(newRecord);
                        ctx.SaveChanges();
                    }
                }
                return returnValue;
            }
            set
            {
                using (var ctx = new OvvioDataContext())
                {
                    var query = from s in ctx.Settings
                                where s.Tag.Equals("IsAdministratorSetup")
                                select s;
                    query.First().Value = value.ToString();
                    ctx.SaveChanges();
                }
            }
        }
    }
}
